<template>
	<view>
		<z-nav-bar :title="['添加问题效果描述', '添加问题原因'][type]"></z-nav-bar>
		<view class="content">
			<view class="flex_sbc">
				<view class="z-font-32 text-w">已选中{{ ['描述标签', '原因'][type] }}</view>
				<view class="z-font-32 uni-red" @click="resetSelItem">删除</view>
			</view>
			<view class="tag-box flex_fsc">
				<view v-for="(tag, index) in selTags.sel" :key="index" class="tag">
					<view style="max-width: 560rpx">{{ tag.map((item) => item.dictValue).join(' --> ') }}</view>
					<image
						:src="setting.oss_pub_domain + '/app-img/icon/close-main-grey.png'"
						@click="deletItem(index)"
					></image>
				</view>
			</view>
			<view v-if="type === 3">
				<view v-for="(item, bindex) in fristList" :key="bindex">
					<view class="flex_sbc uni-mt-60" @click="item.ext = !item.ext">
						<view>
							<text class="text-w z-font-32">{{ item.dictValue }}</text>
							<text class="uni-ml-12 z-font-24 color-C4C7CC">最多可选择5个子标签</text>
						</view>
						<image
							:src="`${setting.oss_pub_domain}/app-img/icon/icon_drop-${item.ext ? 'up' : 'down'}.png`"
							class="icon-size-32"
						></image>
					</view>
					<!-- <view class="item-box-3 flex_fsc flex_wrap" :style="{ height: item.ext ? 'auto' : '84rpx' }"> -->
					<view v-if="!item.ext" class="item-box-3 flex_fsc flex_wrap">
						<view
							v-for="(tag, tindex) in item.children"
							:key="tindex"
							:class="[
								'item',
								selTags.sel.findIndex((item) => item[1].dictCode === tag.dictCode) >= 0
									? 'active'
									: 'unactivated'
							]"
							@click="tagSel(item, tag)"
						>
							{{ tag.dictValue }}
						</view>
					</view>
				</view>
			</view>
			<view v-else class="describe-box flex_sbc">
				<view
					v-for="(item, index) in fristList"
					:key="item.dictCode"
					:class="[
						'item  flex_sbc',
						selTags.fIds.includes(item.dictCode) || selTags.ids.includes(item.dictCode)
							? 'active'
							: 'unactivated'
					]"
					@click="selOneItem(index)"
				>
					<view>{{ item.dictValue }}</view>
					<image
						:src="setting.oss_pub_domain + '/app-img/icon/more-main-grey.png'"
						class="icon-size-32"
					></image>
				</view>
			</view>
		</view>
		<z-no-data v-if="!fristList || !fristList.length"></z-no-data>
		<uni-popup ref="itemBox" type="bottom" @close="clear">
			<view class="popup-box">
				<view class="top flex_sbc">
					<view>
						<view v-if="type">
							<text class="z-font-32">{{ fristList[selIndex].dictValue }}</text>
							<text v-if="type != 1" class="uni-ml-12 z-font-24 color-C4C7CC">以下标签为单选项</text>
						</view>
					</view>
					<view>{{ type ? '' : '选择' }}</view>
					<image
						:src="setting.oss_pub_domain + '/app-img/icon/icon-close-grey.png'"
						class="icon-size"
						@click="itemBox.close()"
					></image>
				</view>
				<scroll-view scroll-y class="scroll">
					<view v-if="type === 0">
						<view>
							<text class="text-w z-font-32">{{ fristList[selIndex].dictValue }}</text>
							<text v-if="type === 0" class="uni-ml-12 z-font-24 color-C4C7CC">以下标签为单选项</text>
						</view>
						<view class="uni-mt-32 flex_sbc flex_wrap">
							<view
								v-for="tag in fristList[selIndex].children"
								:key="tag.dictCode"
								:class="['item', selTags.tmpIds.includes(tag.dictCode) ? 'active' : 'unactivated']"
								@click="tagSel(fristList[selIndex], tag)"
								:style="{
									'font-size':
										tag.dictValue.length > 7
											? '20rpx'
											: tag.dictValue.length > 8
											? '16rpx'
											: '24rpx'
								}"
							>
								{{ tag.dictValue }}
							</view>
							<view class="item"></view>
						</view>
					</view>
					<view v-else-if="type === 1 || type === 2">
						<view>
							<view v-for="children in fristList[selIndex].children" :key="children.dictCode">
								<view v-if="children.hasChildren">
									<text class="text-w z-font-32">{{ children.dictValue }}</text>
									<view class="flex_sbc flex_wrap">
										<view
											v-for="tag in children.children"
											:key="tag.dictCode"
											:class="[
												'item u-line-1',
												selTags.tmpIds.includes(tag.dictCode) ? 'active' : 'unactivated'
											]"
											@click="tagSel(fristList[selIndex], children, tag)"
											:style="{
												'font-size':
													tag.dictValue.length > 7
														? '20rpx'
														: tag.dictValue.length > 8
														? '16rpx'
														: '24rpx'
											}"
										>
											{{ tag.dictValue }}
										</view>
										<view class="item" style="height: 0; visibility: hidden"></view>
										<view class="item" style="height: 0; visibility: hidden"></view>
										<view class="item" style="height: 0; visibility: hidden"></view>
									</view>
								</view>
								<view
									v-else
									:class="[
										'item',
										selTags.tmpIds.includes(children.dictCode) ? 'active' : 'unactivated',
										'uni-mb-16'
									]"
									@click="tagSel(fristList[selIndex], children)"
									:style="{
										'font-size':
											children.dictValue.length > 7
												? '20rpx'
												: children.dictValue.length > 8
												? '16rpx'
												: '24rpx'
									}"
								>
									{{ children.dictValue }}
								</view>
								<view
									style="width: 100%; height: 2rpx; background: #f5f5f5; margin-bottom: 16rpx"
								></view>
							</view>
							<view class="item" style="height: 0; visibility: hidden"></view>
						</view>
					</view>
				</scroll-view>
				<bottom-box :buts="popupButs" :fixed="false" :interval="false" @change="confirm"></bottom-box>
			</view>
		</uni-popup>
		<z-picker ref="picker" :props="pickerProps" :list="pickerList" @change="selItem" :title="title"></z-picker>
		<bottom-box :buts="buts" @change="done"></bottom-box>
	</view>
</template>

<script setup>
import {
	getDescriptionLabelTag,
	getSchemeReasonList,
	getTrainingEnvList,
	getBodyPositionTagList,
	getBodyPositionChildrenList
} from '@/api/common.js';
import { onLoad } from '@dcloudio/uni-app';
import { ref, reactive, getCurrentInstance, computed } from 'vue';
const { proxy: that } = getCurrentInstance();

let eventChannel;
// 初始数据  type 0 问题效果描述 1
const type = ref(0),
	fristList = ref([]),
	selIndex = ref(0),
	multiSelect = ref(false),
	apiList = [getDescriptionLabelTag, getSchemeReasonList, getTrainingEnvList, getBodyPositionTagList];
onLoad((opt) => {
	eventChannel = that.getOpenerEventChannel();
	type.value = parseInt(opt.type || 0);
	if (type.value) multiSelect.value = true;
	const params = [
		{},
		{
			parentCode: opt.parentCode
		},
		{},
		{
			parentCode: opt.parentCode
		}
	];
	fetchData(params[type.value]);
});

function fetchData(params = {}) {
	uni.showLoading({
		title: '数据加载中'
	});
	apiList[type.value](params)
		.then((res) => {
			fristList.value = res.list || res;
			uni.hideLoading();
		})
		.catch(() => {
			uni.hideLoading();
		});
}

// 问题效果描述
const selTags = reactive({
		sel: [],
		ids: [],
		tmpSel: [],
		tmpIds: [],
		fIds: []
	}),
	picker = ref(),
	pickerList = ref([]),
	pickerProps = {
		label: 'dictValue',
		value: 'dictCode'
	},
	tmpArgs = ref([]),
	title = ref('');
const localTagSelList = uni.getStorageSync('tagSelList');
if (localTagSelList) {
	selTags.sel = localTagSelList;
	selTags.ids = localTagSelList.map((item) => item[item.length - 1].dictCode);
	selTags.fIds = Array.from(new Set(localTagSelList.map((item) => item[0].dictCode)));
	uni.removeStorageSync('tagSelList');
}
function selItem(e) {
	const status = tagSel(...tmpArgs.value, e);
	if (status) confirm();
}

function openPicker(res, args) {
	title.value = args[args.length - 1].dictValue;
	pickerList.value = res;
	itemBox.value.close();
	tmpArgs.value = args;
	setTimeout(() => {
		picker.value.open();
	}, 300);
}

function tagSel(...args) {
	console.log(type.value);
	if (args[args.length - 1].hasChildren && type.value) {
		if (type.value === 2) {
			openPicker(args[args.length - 1].children, args);
		} else if (type.value === 3) {
			getBodyPositionChildrenList({
				parentCode: args[args.length - 1].dictCode
			}).then((res) => {
				openPicker(res, args);
			});
		} else {
			apiList[type.value]({
				parentCode: args[args.length - 1].dictCode
			}).then((res) => {
				openPicker(res, args);
			});
		}
		return false;
	}
	const sel = args.map((item) => {
		return {
			dictCode: item.dictCode,
			dictValue: item.dictValue
		};
	});

	const oneListTmp = selTags.tmpSel.filter((item) => item[0].dictCode === args[0].dictCode);
	const index = selTags.tmpSel.findIndex((item) => item[0].dictCode === args[0].dictCode);
	if (multiSelect.value) {
		if (type.value === 3) {
			if (oneListTmp.length >= 5) {
				that.tools.alert('最多选择五个标签');
			} else {
				selTags.tmpSel.push(sel);
				selTags.sel.push(sel);
				selTags.ids.push(sel[sel.length - 1].dictCode);
			}
		} else if (type.value == 1 || type.value == 2) {
			const findex = selTags.tmpSel.findIndex(
				(item) => item[item.length - 1].dictCode == sel[sel.length - 1].dictCode
			);
			if (findex > -1) {
				selTags.tmpSel.splice(findex, 1);
				delList.push(sel);
			} else selTags.tmpSel.push(sel);
		} else {
			if (oneListTmp.length >= 1) selTags.tmpSel[index] = sel;
			else selTags.tmpSel.push(sel);
		}
	} else {
		selTags.tmpSel = [sel];
	}

	selTags.tmpIds = selTags.tmpSel.map((item) => item[item.length - 1].dictCode);
	return true;
}
let delList = [],
	selTwoObj = {};
function confirm() {
	if (type.value == 1 || type.value == 2) {
		selTags.sel.push(
			...selTags.tmpSel.filter((item) => {
				const index = selTags.sel.findIndex(
					(el) => el[el.length - 1].dictCode == item[item.length - 1].dictCode
				);
				return index === -1;
			})
		);
		selTags.sel = selTags.sel.filter((item) => {
			const index = delList.findIndex((el) => el[el.length - 1].dictCode == item[item.length - 1].dictCode);
			return index === -1;
		});
		delList = [];

		selTags.ids = selTags.sel.map((item) => item[item.length - 1].dictCode);
	} else {
		if ([421400, 421405].includes(fristList.value[selIndex.value].dictCode)) {
			if (!selTwoObj.dictCode) {
				getDescriptionLabelTag({
					parentCode: selTags.tmpIds[0]
				}).then((res) => {
					fristList.value[selIndex.value].children = res.list;
				});
				selTwoObj = selTags.tmpSel[0][1];
				return;
			} else {
				selTags.tmpSel[0].splice(1, 0, selTwoObj);
				selTwoObj = {};
			}
		}

		selTags.sel = JSON.parse(JSON.stringify(selTags.tmpSel));
		selTags.ids = JSON.parse(JSON.stringify(selTags.tmpIds));
	}

	selTags.fIds = selTags.sel.map((item) => item[0].dictCode);
	that.$forceUpdate();
	itemBox.value.close();
}

function resetSelItem() {
	selTags.sel = [];
	selTags.ids = [];
	selTags.tmpSel = [];
	selTags.tmpIds = [];
	selTags.fIds = [];
}

function done() {
	if (!selTags.ids.length) return that.tools.alert('请选择标签');
	eventChannel.emit('getTag', {
		obj: selTags.sel,
		code: selTags.sel.map((item) => item[item.length - 1].dictCode).join(',')
	});
	uni.navigateBack();
}

// 打开二级页面
function setData(index, res) {
	console.log(res);
	fristList.value[index].children = res;
	selTags.tmpSel = JSON.parse(JSON.stringify(selTags.sel));
	selTags.tmpIds = JSON.parse(JSON.stringify(selTags.ids));
	itemBox.value.open();
}

function selOneItem(index, tindex) {
	selTwoObj = {}
	selIndex.value = index;
	const item = fristList.value[index];
	if (!item.hasChildren) {
		const si = selTags.sel.findIndex((el) => el[0].dictCode === item.dictCode);
		if (si >= 0) {
			selTags.sel.splice(si, 1);
		} else {
			selTags.sel.push([
				{
					dictCode: item.dictCode,
					dictValue: item.dictValue
				}
			]);
		}
		selTags.ids = selTags.sel.map((item) => item[item.length - 1].dictCode);
		return;
	}
	if (type.value === 0) {
		getDescriptionLabelTag({
			parentCode: item.dictCode
		}).then((res) => {
			setData(index, res.list);
		});
	} else if (type.value === 1) {
		getSchemeReasonList({
			parentCode: item.dictCode
		}).then((res) => {
			const proList = [],
				tmpList = [],
				indexs = [];
			res.forEach((element, index) => {
				if (element.hasChildren) {
					proList.push(
						getSchemeReasonList({
							parentCode: element.dictCode
						})
					);
					indexs.push(index);
				}
			});
			if (proList.length) {
				Promise.all(proList)
					.then((pres) => {
						pres.forEach((p, pi) => {
							res[indexs[pi]].children = p;
						});
						setData(index, res);
					})
					.catch(() => {
						uni.hideLoading();
					});
			} else {
				setData(index, res);
			}
		});
	} else if (type.value === 2) {
		selTags.tmpSel = JSON.parse(JSON.stringify(selTags.sel));
		selTags.tmpIds = JSON.parse(JSON.stringify(selTags.ids));
		itemBox.value.open();
		uni.hideLoading();
	}
}

//  删除
function deletItem(index) {
	console.log(index);
	selTags.sel.splice(index, 1);
	selTags.ids.splice(index, 1);
	selTags.fIds.splice(index, 1);
	selTags.tmpIds.splice(index, 1);
	selTags.tmpSel.splice(index, 1);
	console.log(selTags);
}
// 弹窗
const itemBox = ref('');
const popupButs = [
	{
		label: '确定',
		bgColor: 'uni-color-main-bg'
	}
];

// 底部按钮
const buts = [
	{
		label: '确定',
		bgColor: 'uni-color-main-bg'
	}
];
</script>

<style lang="scss" scoped>
@import 'add-item.scss';
</style>
